import {
	isIOS,
	isWeixin,
	isqq,
	isAndroid,
	isHuwei,
	flvCommon,
	hasClass,
	toggleClass,
	addClass,
	removeClass,
	sleep
} from '../../common/utils'
import EventEmitter from '../../common/EventEmitter'
import {playerEvents} from '../playerEvents'
import flv from 'flv.js'
import './styles/common.css'
import './styles/fullscreenPlayer.scss'
function loadInitLine(serverUrl,flvSupport){
 	var urlArr = []
	if(flvSupport){
		serverUrl.forEach((item,index)=>{
			if(item.flv && typeof(item.flv) === 'string'){
				urlArr.push(item.flv)
			}
		})
	}else{
		serverUrl.forEach((item,index)=>{
			urlArr.push(item.hls)
		})
	}
 	return {urlArr,serverUrl};
}
function wxPlayVideo(video) {
	WeixinJSBridge && WeixinJSBridge.invoke('getNetworkType', {}, function(e) {
		Promise.resolve(video.play()).catch(err => {
			console.log(err)
		});
	});
}

function playAuto() {
	var self = this;
	Promise.resolve(self.play()).catch(err => {
		console.log(err)
	})
	if (isWeixin) {
		var evtFns = [];
		try {
			wxPlayVideo(self);
			return;
		} catch (ex) {
			evtFns.push("WeixinJSBridgeReady", function evt() {
				wxPlayVideo(self);
				for (var i = 0; i < evtFns.length; i += 2) document.removeEventListener(evtFns[i], evtFns[i + 1], false);
			});
			document.addEventListener("WeixinJSBridgeReady", evtFns[evtFns.length - 1], false);
		}
	}
}
HTMLVideoElement.prototype.playAuto = playAuto;
export default class fullScreenPlayer {
	//视频开始卡顿时间
	static emptyTime = 0;
	//视频加载好后开始播放的时间
	static fullTime = 0;
	//在发送时间内视频卡顿的时间
	static totalTime = 0;
	static sendTimer = null;
	static videoControlTimer = null;
	constructor() {
		let args = arguments[0]
		let defaultConfig = {mode:0,sendTime:10,autoPlay:true}
		Object.assign(defaultConfig,args)
		for (var i in defaultConfig) {
			if({}.hasOwnProperty.call(defaultConfig,i)){
				this[i] = defaultConfig[i];
			}
		}
		if(typeof(this.el) === 'string' && document.getElementById(this.el)){
			this.el = document.getElementById(this.el)
		}else{
			console.error('el参数为元素ID,该参数必传!')
			return false
		}
		if(this.sleep){
			let tipsDiv = '<div class="shang-mai-tips">(´・ω・｀)老师上麦中<span class="dot"></span></div>'
			this.el.innerHTML = tipsDiv
			return sleep(this.sleep).then(()=>{
				this.init()
				return this
			})
		}else{
			this.init()
		}
	}
	init() {
		if(!this.openHls){
			this.flvSupport = flvCommon.flvSupport
			this.openWebGl = this.openWebGl && isIOS
		}else{
			this.flvSupport = false
			this.openWebGl = false
		}
		let obj
		if(this.openWebGl){
			obj = loadInitLine(this.watchServer,this.openWebGl)
		}else{
			obj = loadInitLine(this.watchServer,this.flvSupport)
		}
		this.autoChange = true
		this.watchServer = obj.serverUrl
		this.urlArr = obj.urlArr
		this.hlsUrl = obj.urlArr[this.currentHlsIndex]
		this.playerEvents = playerEvents
		this.openFlvError = true
		let that = this
		this.emitter = new EventEmitter()
		Promise.resolve().then(() => {
			this.emitter.trigger(playerEvents.SET_PLAYER_INDEX, this.currentHlsIndex)
		})
		if (this.mode === 0) {
			if(this.openWebGl){
				this.el.innerHTML =
					'<div class="fullscreen-player-wrap fullscreen-player-wrap-mode0"><div class="fullscreen-play-btn">\
						<div class="player_btn_bg"></div>\
						<p>正在直播中，戳这里看直播。</p>\
					</div>\
					<div class="choose-line-wrap"><div class="choose-line-innerwrap fl fix" style="display:none"><div class="choose-line-inner-leftwrap fl">线路选择  :</div><div class="choose-line-inner-rightwrap fr"><span class="line-name">'+this.watchServer[this.currentHlsIndex].name +'</span><i class="choose-line-icon"></i></div></div><div class="set-auto-change-wrap fr" style="display:none"><a href="javascript:;" class="mode0-auto-change-span">关闭自动切换流</a></div></div>\
					<div class="flv-error-tips" style="display:none">当前flv无法播放,正在帮您切换,请稍等</div>\
					<p class="fullscreen-video-load" style="display:none"></p>\
					<canvas id="video-js" class="video-js"></canvas></div>';
			}else{
				this.el.innerHTML =
					'<div class="fullscreen-player-wrap fullscreen-player-wrap-mode0"><div class="fullscreen-play-btn">\
						<div class="player_btn_bg"></div>\
						<p>正在直播中，戳这里看直播。</p>\
					</div>\
					<div class="choose-line-wrap"><div class="choose-line-innerwrap fl fix" style="display:none"><div class="choose-line-inner-leftwrap fl">线路选择  :</div><div class="choose-line-inner-rightwrap fr"><span class="line-name">'+this.watchServer[this.currentHlsIndex].name +'</span><i class="choose-line-icon"></i></div></div><div class="set-auto-change-wrap fr" style="display:none"><a href="javascript:;" class="mode0-auto-change-span">关闭自动切换流</a></div></div>\
					<div class="flv-error-tips" style="display:none">当前flv无法播放,正在帮您切换,请稍等</div>\
					<p class="fullscreen-line-load" style="display:none">当前流不稳定,正在帮您切换线路,请亲们耐心等待...</p>\
					<p class="fullscreen-video-load" style="display:none"></p>\
					<video class="video-js" preload="auto" x-webkit-airplay="true" webkit-playsinline="" x5-video-player-type="h5" x5-video-player-fullscreen="true" playsinline="" width="100%" height="100%" src="' +
					this.hlsUrl + '"></video></div>';
			}
		} else {
			if(this.openWebGl){
				this.el.innerHTML =
					'<div class="fullscreen-player-wrap fullscreen-player-wrap-mode1"><div class="fullscreen-play-btn-mode2">\
					<div class="fullscreen-play-btn-mode2-inner">\
						<div class="player_btn_bg_2"></div>\
						<div class="player_btn_mode2_tips">点击观看直播</div>\
					</div>\
				</div>\
				<div class="flv-error-tips" style="display:none">当前flv无法播放,正在帮您切换,请稍等</div>\
				<p class="fullscreen-video-load" style="display:none"></p>\
				<div class="video-control-wrap"><div class="video-control-left-wrap fl"><span class="video-control-play-live" style="margin-left:10px">直播</span></div><div class="video-control-right-wrap fr"><span class="change-url-span" style="display:none">' +
					this.watchServer[this.currentHlsIndex].name +
					'</span><i class="fullscreen-icon"></i></div></div>\
				<div class="video-inner-box" style="background: url(' +
					this.liveImg +
					') 50% 50% / cover no-repeat rgb(0, 0, 0);">\
				<canvas id="video-js" class="video-js" style="width:100%;height:100%"></canvas>\
				</div></div>';
			}else{
				if ((isWeixin || isqq) && isAndroid) {
					this.el.innerHTML =
						'<div class="fullscreen-player-wrap fullscreen-player-wrap-mode1"><div class="fullscreen-play-btn-mode2">\
						<div class="fullscreen-play-btn-mode2-inner">\
							<div class="player_btn_bg_2"></div>\
							<div class="player_btn_mode2_tips">点击观看直播</div>\
						</div>\
					</div>\
					<div class="flv-error-tips" style="display:none">当前flv无法播放,正在帮您切换,请稍等</div>\
					<p class="fullscreen-line-load" style="display:none">当前流不稳定,正在帮您切换线路,请亲们耐心等待...</p>\
					<p class="fullscreen-video-load" style="display:none"></p>\
					<div class="video-control-wrap"><div class="video-control-left-wrap fl"><i class="video-control-play-icon"></i><span class="video-control-play-live">直播</span></div><div class="video-control-right-wrap fr"><span class="auto-change-span" style="display:none">关闭自动切换流</span><span class="change-url-span" style="display:none">' +
						this.watchServer[this.currentHlsIndex].name +
						'</span><i class="fullscreen-icon"></i></div></div>\
					<div class="video-inner-box" style="background: url(' +
						this.liveImg +
						') 50% 50% / cover no-repeat rgb(0, 0, 0);">\
					<video class="video-js" preload="auto" x5-video-player-type="h5" x5-video-player-fullscreen="true" x-webkit-airplay="allow" webkit-playsinline="true" width="100%" height="3000" src="' +
						this.hlsUrl + '" style="object-position:0px 0px;background-size: cover;"></video>\
					</div></div>';
				} else {
					this.el.innerHTML =
						'<div class="fullscreen-player-wrap fullscreen-player-wrap-mode1"><div class="fullscreen-play-btn-mode2">\
						<div class="fullscreen-play-btn-mode2-inner">\
							<div class="player_btn_bg_2"></div>\
							<div class="player_btn_mode2_tips">点击观看直播</div>\
						</div>\
					</div>\
					<div class="flv-error-tips" style="display:none">当前flv无法播放,正在帮您切换,请稍等</div>\
					<p class="fullscreen-line-load" style="display:none">当前流不稳定,正在帮您切换线路,请亲们耐心等待...</p>\
					<p class="fullscreen-video-load" style="display:none"></p>\
					<div class="video-control-wrap"><div class="video-control-left-wrap fl"><i class="video-control-play-icon"></i><span class="video-control-play-live">直播</span></div><div class="video-control-right-wrap fr"><span class="auto-change-span" style="display:none">关闭自动切换流</span><span class="change-url-span" style="display:none">' +
						this.watchServer[this.currentHlsIndex].name +
						'</span><i class="fullscreen-icon"></i></div></div>\
					<div class="video-inner-box" style="background: url(' +
						this.liveImg +
						') 50% 50% / cover no-repeat rgb(0, 0, 0);">\
					<video class="video-js" preload="auto" webkit-playsinline playsinline type="application/x-mpegURL"  width="100%" height="100%" src="' +
						this.hlsUrl + '"></video>\
					</div></div>';
				}
			}
		}
		this.media = this.el.querySelector('.video-js')
		this.palyerWrap = this.el.querySelector('.fullscreen-player-wrap')
		this.videoLoad = this.el.querySelector('.fullscreen-video-load')
		this.lineLoad = this.el.querySelector('.fullscreen-line-load')
		this.flvErrorTips = this.el.querySelector('.flv-error-tips')
		this.videoLoad.innerHTML = `<svg height="100%" version="1.1" viewBox="0 0 22 22">
			<svg x="7" y="1">
					<circle class="xchatplayer-loading-dot xchatplayer-loading-dot-0" cx="4" cy="4" r="2"></circle>
			</svg>
			<svg x="11" y="3">
					<circle class="xchatplayer-loading-dot xchatplayer-loading-dot-1" cx="4" cy="4" r="2"></circle>
			</svg>
			<svg x="13" y="7">
					<circle class="xchatplayer-loading-dot xchatplayer-loading-dot-2" cx="4" cy="4" r="2"></circle>
			</svg>
			<svg x="11" y="11">
					<circle class="xchatplayer-loading-dot xchatplayer-loading-dot-3" cx="4" cy="4" r="2"></circle>
			</svg>
			<svg x="7" y="13">
					<circle class="xchatplayer-loading-dot xchatplayer-loading-dot-4" cx="4" cy="4" r="2"></circle>
			</svg>
			<svg x="3" y="11">
					<circle class="xchatplayer-loading-dot xchatplayer-loading-dot-5" cx="4" cy="4" r="2"></circle>
			</svg>
			<svg x="1" y="7">
					<circle class="xchatplayer-loading-dot xchatplayer-loading-dot-6" cx="4" cy="4" r="2"></circle>
			</svg>
			<svg x="3" y="3">
					<circle class="xchatplayer-loading-dot xchatplayer-loading-dot-7" cx="4" cy="4" r="2"></circle>
			</svg>
	</svg>`
		this.media.controls = false
		this.orientationchange = this.orientationchange.bind(this)
		this.judgeOnorientation()
		this.handleOnorientation()
		//线路切换
		if (this.urlArr.length > 0 && !this.flvSupport && !this.openWebGl) {
			if (this.mode === 0) {
				this.chooseLineInnerwrap = this.el.querySelector('.choose-line-innerwrap')
				this.chooseLineInnerwrap.style.display = 'block'
				let chooseLineStart =
					'<div class="choose-line-mode0-wrap"><div class="line-wrap">'
				let chooseLineMiddle = ''
				this.watchServer.forEach((item, index) => {
					if (this.currentHlsIndex === index) {
						chooseLineMiddle += '<div class="line-wrap-item active" data-index="' + index + '" data-hls="' + item.hls +
							'">' + item.name + '</div>'
					} else {
						chooseLineMiddle += '<div class="line-wrap-item" data-index="' + index + '" data-hls="' + item.hls + '">' +
							item.name + '</div>'
					}
				})
				let chooseLineEnd = '</div></div>'
				this.chooseLineInnerRight = this.el.querySelector('.choose-line-inner-rightwrap')
				this.chooseLineInnerRight.insertAdjacentHTML('beforeEnd', chooseLineStart + chooseLineMiddle + chooseLineEnd)
				this.chooseLineInnerRight.addEventListener("click",(e)=>{
					if (hasClass(this.chooseLineInnerRight, 'active')) {
						removeClass(this.chooseLineInnerRight, 'active')
					} else {
						addClass(this.chooseLineInnerRight, 'active')
					}
				})
				this.el.querySelector('.choose-line-mode0-wrap').addEventListener("click", (e) => {
					if(e.stopPropagation){
					  e.stopPropagation()
					}else{
						e.cancelBubble=true
					}
					let target = e.target || e.srcElement
					if ([...target.classList].includes('line-wrap-item')) {
						if (hasClass(target, 'active')) {
							return false
						}
						that.changePlayer(target.dataset.hls, target.dataset.index)
					}
				})
			} else {
				this.el.querySelector('.change-url-span').style.display = 'inline-block'
				let chooseLineStart =
					'<div class="choose-line-mode2-wrap"><div class="choose-line-mode2-bg-cover"></div><div class="line-wrap">'
				let chooseLineMiddle = ''
				this.watchServer.forEach((item, index) => {
					if (this.currentHlsIndex === index) {
						chooseLineMiddle += '<div class="line-wrap-item active" data-index="' + index + '" data-hls="' + item.hls +
							'">' + item.name + '</div>'
					} else {
						chooseLineMiddle += '<div class="line-wrap-item" data-index="' + index + '" data-hls="' + item.hls + '">' +
							item.name + '</div>'
					}
				})
				let chooseLineEnd = '</div></div>'
				this.el.querySelector('.fullscreen-player-wrap').insertAdjacentHTML('beforeEnd', chooseLineStart + chooseLineMiddle + chooseLineEnd)

				function lineCoverShow() {
					if (hasClass(this.el.querySelector('.choose-line-mode2-wrap'), 'active')) {
						removeClass(this.el.querySelector('.choose-line-mode2-wrap'), 'active')
					} else {
						addClass(this.el.querySelector('.choose-line-mode2-wrap'), 'active')
					}
				}
				this.el.querySelector('.change-url-span').addEventListener("click", () => {
					lineCoverShow.call(this)
				})
				this.el.querySelector('.choose-line-mode2-bg-cover').addEventListener("click", () => {
					lineCoverShow.call(this)
				})
				this.el.querySelector('.line-wrap').addEventListener("click", (e) => {
					let target = e.target || e.srcElement
					if ([...target.classList].includes('line-wrap-item')) {
						if (hasClass(target, 'active')) {
							return false
						}
						that.changePlayer(target.dataset.hls, target.dataset.index)
						lineCoverShow.call(this)
					}
				})
			}
			//需要监听自动切换
			this.emitter.on(playerEvents.SET_PLAYER_INDEX, (index) => {
				if(that.mode !== 0){
					if(this.el.querySelector('.change-url-span')){
						this.el.querySelector('.change-url-span').innerText = that.watchServer[index].name;
					}
				}else{
					this.el.querySelector('.choose-line-inner-rightwrap .line-name').innerText = that.watchServer[index].name;
				}
				[...this.el.querySelectorAll('.line-wrap-item')].forEach((item,elindex) => {
					removeClass(item, 'active')
					if(elindex == index){
						addClass(item, 'active')
					}
				})
			})
		}
		//播放器初始化完成
		Promise.resolve().then(() => {
			this.emitter.trigger(playerEvents.H5_PLAYER_LOADED)
		})
		//控制自动切换流按钮显示
		if(isIOS && this.sendTime && !this.openWebGl){
			function changeAuto(selector,that){
				if (that.autoChange) {
					that.setAutoChange(false)
					that.el.querySelector(selector).innerHTML = '开启自动切换流'
				} else {
					that.setAutoChange(true)
					that.el.querySelector(selector).innerHTML = '关闭自动切换流'
				}
			}
			if(this.mode !== 0){
				this.el.querySelector('.auto-change-span').style.display = 'inline-block'
				//是否自动切换
				this.el.querySelector('.auto-change-span').addEventListener("click", function() {
					changeAuto('.auto-change-span',this)
				}.bind(this))
			}else{
				this.el.querySelector('.set-auto-change-wrap').style.display = 'block'
				this.el.querySelector('.set-auto-change-wrap').addEventListener("click", function() {
					changeAuto('.mode0-auto-change-span',this)
				}.bind(this))
			}
		}
		
		//支持flv播放则创建flv播放器
		if(isAndroid && this.flvSupport){
			if(document.body.classList.contains('flv-container-wrap')){
				document.body.classList.remove('flv-container-wrap')
			}
			document.body.classList.add('flv-container-wrap')
			fullScreenPlayer.flvPlayer = flvCommon.createFlvPlayer(this.hlsUrl, this.media)
			fullScreenPlayer.flvPlayer.on(flv.Events.ERROR, function() {
				if(this.openFlvError){
					if(document.body.classList.contains('flv-container-wrap')){
						document.body.classList.remove('flv-container-wrap')
					}
					this.openFlvError = false
					this.lineLoad.style.display = 'none'
					this.videoLoad.style.display = 'none'
					this.flvErrorTips.style.display = 'block'
					setTimeout(function() {
						that.emitter.trigger(playerEvents.FLV_ERROR)
						if (typeof(that.flvErrorCallback) === 'function') {
							that.flvErrorCallback()
						}
					}, 1000)
				}
			}.bind(this))
		}
		//检查是否正在buffering用来显示loading
		this.enableloadingChecker = false
		// this.initloadingChecker()
		if(this.mode === 0){
			this.fullScreenPlayBtn = this.el.querySelector('.fullscreen-play-btn')
		}else{
			this.fullScreenPlayBtnMode2 = this.el.querySelector('.fullscreen-play-btn-mode2')
			this.fullScreenIcon = this.el.querySelector('.fullscreen-icon')
			this.videoControlIcon = this.el.querySelector('.video-control-play-icon')
			this.videoControlWrap = this.el.querySelector('.video-control-wrap')
		}
		//自动播放
		if (this.autoPlay) {
			if(this.openWebGl){
				if (this.mode === 0) {
					this.fullScreenPlayBtn.style.display = 'none'
				} else {
					this.fullscreenPlayBtnMode2.style.display = 'none'
				}
				this.videoLoad.style.display = 'block'
				this.initNodePlayer(true)
			}else{
				if(isWeixin || isqq){
					if(isIOS || (isAndroid && this.flvSupport)){
						if (this.mode === 0) {
							this.fullScreenPlayBtn.style.display = 'none'
						} else {
							this.fullScreenPlayBtnMode2.style.display = 'none'
						}
					}
					this.enableloadingChecker = true
					if(isIOS){
						this.play()
					}else if(this.flvSupport && fullScreenPlayer.flvPlayer){
						that.flvPlayerPlay(fullScreenPlayer.flvPlayer)
					}
				}
			}
		}
		//按钮点击播放
		if (this.mode === 0) {
			this.fullScreenPlayBtn.addEventListener('click', function() {
				if(that.videoLoad.style.display === 'block'){
					return false
				}
				this.style.display = 'none'
				if (that.flvSupport) {
					that.flvPlayerPlay(fullScreenPlayer.flvPlayer)
				} else if(that.openWebGl){
					if(that.nodePlayer){
						that.nodePlayer.start(that.hlsUrl)
					}
				}else{
					that.play()
				}
			})
		} else {
			function mode1Play() {
				if(that.lineLoad.style.display === 'block'){
					return false
				}
				that.fullScreenPlayBtnMode2.style.display = 'none'
				if (that.flvSupport) {
					that.flvPlayerPlay(fullScreenPlayer.flvPlayer)
				} else if(that.openWebGl){
					if(that.nodePlayer){
						that.nodePlayer.start(that.hlsUrl)
					}
				}else {
					that.play()
				}
			}
			if(!this.openWebGl){
				this.el.querySelector('.player_btn_bg_2').addEventListener('click', function(e) {
					if(e.stopPropagation){
						e.stopPropagation()
					}else{
						e.cancelBubble=true
					}
					mode1Play()
				})
			}
			if(!this.openWebGl){
				this.el.querySelector('.video-control-play-icon').addEventListener('click', function(e) {
					if(e.stopPropagation){
					  e.stopPropagation()
					}else{
						e.cancelBubble=true
					}
					mode1Play()
				})
			}
			//安卓微信、QQ浏览器全屏按钮隐藏
			if(isAndroid && isqq || isAndroid && isWeixin){
				this.fullScreenIcon.style.display = 'none'
			}else{
				this.openFullscreen = false
				//点击全屏
				this.fullScreenIcon.addEventListener('click', (e) => {
					if(e.stopPropagation){
					  e.stopPropagation()
					}else{
						e.cancelBubble=true
					}
					if(!this.openFullscreen){
						this.palyerWrap.setAttribute('data-fullscreen','fullscreen')
						this.fullScreenIcon.style.backgroundImage =
							`url(${require('./images/icon-cancel-fullscreen.png')})`
						this.openFullscreen = true
						
					}else{
						this.palyerWrap.setAttribute('data-fullscreen','normal')
						this.fullScreenIcon.style.backgroundImage =
							`url(${require('./images/icon-fullscreen.png')})`
						this.openFullscreen = false
					}
					this.emitter.trigger(playerEvents.H5_PLAYER_FULLSCREEN,this.openFullscreen)
				})
			}
			this.media.addEventListener("click", (e) => {
				if(e.stopPropagation){
	        e.stopPropagation()
        }else{
					e.cancelBubble=true
        }
				if (fullScreenPlayer.videoControlTimer) {
					clearTimeout(fullScreenPlayer.videoControlTimer)
				}
				this.emitter.trigger(playerEvents.H5_PLAYER_CLICK)
				if(this.videoControlWrap){
					if (!hasClass(this.videoControlWrap, 'active')) {
						addClass(this.videoControlWrap, 'active')
					} else {
						removeClass(this.videoControlWrap, 'active')
					}
					fullScreenPlayer.videoControlTimer = setTimeout(() => {
						if(this.videoControlWrap){
							if (hasClass(this.videoControlWrap, 'active')) {
								removeClass(this.videoControlWrap, 'active')
							}
						}
					}, 4000)
				}
			})
		}
		this.media.addEventListener("playing", () => {
			this.videoLoad && (this.videoLoad.style.display = 'none')
			if (fullScreenPlayer.emptyTime) {
				fullScreenPlayer.fullTime = new Date().getTime();
				let pretime = fullScreenPlayer.fullTime - fullScreenPlayer.emptyTime;
				fullScreenPlayer.totalTime += pretime;
				fullScreenPlayer.emptyTime = 0;
			}
		}, false);
		this.media.addEventListener("waiting", () => {
			this.videoLoad && (this.videoLoad.style.display = 'block')
			fullScreenPlayer.emptyTime = new Date().getTime();
			fullScreenPlayer.fullTime = 0;
		}, false);
		this.media.addEventListener("play", () => {
			this.media.style.opacity = '1'
			if (this.mode === 0) {
				this.fullScreenPlayBtn.style.display = 'none'
			} else {
				this.fullScreenPlayBtnMode2.style.display = 'none'
			}
			that.emitter.trigger(playerEvents.NATIVE_PLAYER_PLAY)
			if (typeof(that.playCallback) === 'function') {
				that.playCallback()
			}
		}, false)
		//安卓退出全屏
		this.media.addEventListener('x5videoexitfullscreen', ()=> {
			try{
				this.videoLoad.style.display = 'none'
				if(this.flvSupport){
					this.flvPlayerPause()
				}else{
					if (this.mode == 0) {
						this.media.style.opacity = '0'
						this.fullScreenPlayBtn.style.display = 'block'
					} else {
						if (hasClass(this.videoControlWrap, 'active')) {
							removeClass(this.videoControlWrap, 'active')
						}
						this.media.style.opacity = '0'
						this.fullScreenPlayBtnMode2.style.display = 'block'
						this.videoControlIcon.style.backgroundImage =
							`url(${require('./images/video-control-play.png')})`
					}
				}
			}catch(e){
				console.log(e)
			}
		}, false)
		//ios退出全屏
		this.media.addEventListener('webkitendfullscreen', () => {
			this.media.style.opacity = '0'
			this.videoLoad.style.display = 'none'
			if (this.mode === 0) {
				this.fullScreenPlayBtn.style.display = 'block'
			} else {
				if (hasClass(this.videoControlWrap, 'active')) {
					removeClass(this.videoControlWrap, 'active')
				}
				this.fullScreenPlayBtnMode2.style.display = 'block'
				this.videoControlIcon.style.backgroundImage =
					`url(${require('./images/video-control-play.png')})`
			}
		}, false);
		this.media.addEventListener("pause", () => {
			that.emitter.trigger(playerEvents.NATIVE_PLAYER_PAUSE)
				if (isHuwei && (!isqq || !isWeixin)) {
					this.videoLoad.style.display = 'none'
					if (this.mode === 0) {
						this.media.style.opacity = '0'
						this.fullScreenPlayBtn.style.display = 'block'
					} else {
						if (hasClass(this.videoControlWrap, 'active')) {
							removeClass(this.videoControlWrap, 'active')
						}
						this.media.style.opacity = '0'
						if (this.liveImg) {
							this.el.querySelector('.video-box').style.background = 'url(' + this.liveImg +
								') 50% 50% / cover no-repeat rgb(0, 0, 0);'
						}
						this.fullScreenPlayBtnMode2.style.display = 'block'
					}
				}
		}, false)
		this.media.addEventListener('error', () => {
			try{
				if(this.media && this.media.error && !this.flvSupport){
					this.enableloadingChecker = false
					if(this.noticeWrap && this.noticeWrap.parentNode){
						this.removeRefresh()
						this.noticeWrap.parentNode.removeChild(this.noticeWrap)
						this.noticeWrap = null
					}
					if(this.mode === 0){
						if(this.fullScreenPlayBtn){
							this.fullScreenPlayBtn.style.display = 'none'
						}
					}else{
						if(this.fullScreenPlayBtnMode2){
							this.fullScreenPlayBtnMode2.style.display = 'none'
						}
						this.videoControlIcon.style.backgroundImage =
							`url(${require('./images/video-control-play.png')})`
						if (this.videoControlWrap && hasClass(this.videoControlWrap, 'active')) {
							removeClass(this.videoControlWrap, 'active')
						}
					}
					if(this.videoLoad){
						this.videoLoad.style.display = 'none'
					}
					let htmlString = `<div class="notice-wrap">直播加载失败，请刷新重试<div class="inner-tips">错误码:${this.media.error.code}</div></div>`
					this.el.insertAdjacentHTML('beforeEnd', htmlString)
					this.noticeWrap = this.el.querySelector('.notice-wrap')
					this.noticeWrap.querySelector('.inner-tips').insertAdjacentHTML('beforeBegin',`<svg t="1568001251299" title="点我刷新" class="refresh-player-icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2224" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M208.784092 236.691565A409.380572 409.380572 0 0 1 921.106287 512h102.345143A511.725715 511.725715 0 0 0 132.53696 168.12032l-56.289828-51.172572-41.449783 238.464183 231.811749-66.524343zM814.667338 787.308435A409.380572 409.380572 0 0 1 102.345143 512H0a511.725715 511.725715 0 0 0 890.91447 343.87968l56.289828 51.172572 41.961509-237.952457-231.811749 66.524342z" p-id="2225" fill="#ffffff"></path></svg>`)
					this.addRefresh()
				}
			}catch(e){
				console.log(e)
			}
		}, false)
		this.enableFluencyChecker = true
		if (this.sendTime && !this.flvSupport) {
			fullScreenPlayer.sendTimer = setInterval(function() {
					var userAgent = navigator.userAgent;
					var _settime = new Date().getTime();
					if (fullScreenPlayer.emptyTime > 0 && fullScreenPlayer.fullTime == 0) {
						fullScreenPlayer.totalTime = _settime - fullScreenPlayer.emptyTime;
						fullScreenPlayer.emptyTime = _settime;
					}
					if (userAgent.indexOf("Android") < 0)
						this.sendBegainInfo();
					fullScreenPlayer.totalTime = 0
			}.bind(this), this.sendTime * 1000)
		}
	}
	findCurrentUrlIndex(url) {
		let index = this.urlArr.findIndex(item => item === url)
		if (index !== -1) {
			return index
		} else {
			return 0
		}
	}
	play() {
		if(this.noticeWrap){
			this.noticeWrap.style.display = 'none'
		}
		if(this.lineLoad.style.display === 'block'){
			return false
		}
		this.videoLoad.style.display = 'block' 
		if (this.media.paused) {
			this.enableloadingChecker = true
			if (this.mode !== 0) {
				this.videoControlIcon.style.backgroundImage =
					`url(${require('./images/video-control-pause.png')})`
			}
			this.enableFluencyChecker = true
			this.media.playAuto()
		} else {
			this.pause()
		}
	}
	flvPlayerPlay(){
		if(this.noticeWrap){
			this.noticeWrap.style.display = 'none'
		}
		this.videoLoad.style.display = 'block' 
		let that = this,flvPlayer = fullScreenPlayer.flvPlayer
		if(this.lineLoad.style.display === 'block'){
			return false
		}
		if(!flvPlayer){
			flvPlayer = fullScreenPlayer.flvPlayer = flvCommon.createFlvPlayer(this.hlsUrl, this.media)
		}
		if (this.media.paused) {
			this.enableloadingChecker = true
			if (that.mode !== 0) {
				this.videoControlIcon.style.backgroundImage =
					`url(${require('./images/video-control-pause.png')})`
			}
			flvPlayer.unload()
			flvPlayer.load()
			Promise.resolve(flvPlayer.play()).then(()=>{
				this.videoLoad.style.display = 'none'
				fullScreenPlayer.flvPlayerPlaying = true
				this.judgeIsSeek()
				if(this.autoSeek){
					this.openLazySeek()
				}
			}).catch(function(err){
				console.log(err)
			})
		} else {
			this.flvPlayerPause()
		}
	}
	pause() {
		this.enableFluencyChecker = false
		this.enableloadingChecker = false
		if(!this.videoLoad){
			return
		}
		this.videoLoad.style.display = 'none'
		if (this.mode !== 0) {
			this.fullScreenPlayBtnMode2.style.display = 'block'
			this.videoControlIcon.style.backgroundImage =
				`url(${require('./images/video-control-play.png')})`
			if (hasClass(this.videoControlWrap, 'active')) {
				removeClass(this.videoControlWrap, 'active')
			}
		}
		this.media.pause()
	}
	flvPlayerPause(){
		this.enableloadingChecker = false
		if(!this.videoLoad){
			return
		}
		this.videoLoad.style.display = 'none'
		if (this.mode !== 0) {
			this.fullScreenPlayBtnMode2.style.display = 'block'
			this.videoControlIcon.style.backgroundImage =
				`url(${require('./images/video-control-play.png')})`
			if (hasClass(this.videoControlWrap, 'active')) {
				removeClass(this.videoControlWrap, 'active')
			}
		}else{
			this.fullScreenPlayBtn.style.display = 'block'
		}
		if(fullScreenPlayer.lazySeekTimer){
			clearInterval(fullScreenPlayer.lazySeekTimer)
			fullScreenPlayer.lazySeekTimer = null
		}
		fullScreenPlayer.flvPlayerPlaying = false
		flvCommon.destroyFlvPlayer(fullScreenPlayer.flvPlayer)
		fullScreenPlayer.flvPlayer = null
		this.emitter.trigger(playerEvents.NATIVE_PLAYER_PAUSE)
	}
	exportPlay (){
		if(this.flvSupport){
			this.flvPlayerPlay()
		}else{
			this.play()
		}
	}
	exportPause(){
		if(this.flvSupport){
			this.flvPlayerPause()
		}else{
			this.pause()
		}
	}
	sendBegainInfo() {
		let call_time = new Date().getTime();
		let Fluency = (1 - fullScreenPlayer.totalTime / (this.sendTime * 1000)).toFixed(2);
		//流质量不行,自动切换
		if (Fluency < 0.69 && this.autoChange && this.enableFluencyChecker) {
			if (this.Mictime) {
				//上麦两分钟内不能切换
				let del_time = call_time - this.Mictime;
				if (del_time > 1200) {
					this.currentHlsIndex++
					if (this.currentHlsIndex >= this.urlArr.length) {
						this.currentHlsIndex = 0
					}
					if(this.noticeWrap && this.noticeWrap.parentNode){
						this.noticeWrap.parentNode.removeChild(this.noticeWrap)
						this.noticeWrap = null
					}
					this.videoLoad.style.display = 'none'
					this.lineLoad.style.display = 'block'
					setTimeout(() => {
						this.changePlayer(this.urlArr[this.currentHlsIndex], this.currentHlsIndex)
					}, 1000)
				}
			}else{
				this.currentHlsIndex++
				if (this.currentHlsIndex >= this.urlArr.length) {
					this.currentHlsIndex = 0
				}
				this.videoLoad.style.display = 'none'
				this.lineLoad.style.display = 'block'
				setTimeout(() => {
					this.changePlayer(this.urlArr[this.currentHlsIndex], this.currentHlsIndex)
				}, 1000)
			}
		}
	}
	changePlayer(url, index, autoPlay = true) {
		if(this.noticeWrap){
			this.noticeWrap.style.display = 'none'
		}
		fullScreenPlayer.emptyTime = 0
		fullScreenPlayer.fullTime = 0
		fullScreenPlayer.totalTime = 0
		this.currentHlsIndex = index
		this.emitter.trigger(playerEvents.SET_PLAYER_INDEX, this.currentHlsIndex)
		this.lineLoad.style.display = 'none'
		if(!this.media.paused){
			this.media.pause()
		}
		this.media.src = url
		if(autoPlay){
			this.enableloadingChecker = true
			if (this.mode === 0) {
				this.fullScreenPlayBtn.style.display = 'none'
			} else {
				this.fullScreenPlayBtnMode2.style.display = 'none'
			}
			this.play()
		}
	}
	setAutoChange(change) {
		this.autoChange = change
	}
	destroyFunc(){
		this.emitter.trigger('destroy')
		if(this.media){
			// fix video destroy https://stackoverflow.com/questions/3258587/how-to-properly-unload-destroy-a-video-element
			this.media.removeAttribute('src') // empty source
			this.media.load()
		}
	}
	destroy() {
		if(this.noticeWrap && this.noticeWrap.parentNode){
			this.noticeWrap.parentNode.removeChild(this.noticeWrap)
			this.noticeWrap = null
		}
		if(this.openWebGl){
			if(this.nodePlayer){
				this.nodePlayer.destroy()
				this.nodePlayer = null
			}
		}else{
			if (fullScreenPlayer.flvPlayer) {
				if(fullScreenPlayer.lazySeekTimer){
					clearInterval(fullScreenPlayer.lazySeekTimer)
					fullScreenPlayer.lazySeekTimer = null
				}
				flvCommon.destroyFlvPlayer(fullScreenPlayer.flvPlayer)
			}
			if(this.loadingChecker){
				clearInterval(this.loadingChecker)
				this.loadingChecker = null
			}
			clearInterval(fullScreenPlayer.sendTimer)
			fullScreenPlayer.sendTimer = null
			fullScreenPlayer.flvPlayer = null
			fullScreenPlayer.videoControlTimer = null
			clearTimeout(fullScreenPlayer.videoControlTimer)
			this.removeEvent()
			if(!this.media.paused){
				this.exportPause()
				this.once(playerEvents.NATIVE_PLAYER_PAUSE,()=>{
					this.destroyFunc()
				})
			}else{
				this.destroyFunc()
			}
			this.el.innerHTML = ''
			this.media = null
			this.palyerWrap = null
			this.videoLoad = null
			this.lineLoad = null
			this.flvErrorTips = null
			this.el = null
		}
	}
	on(event, listener) {
		this.emitter.on(event, listener)
	}
	off(event, listener) {
		this.emitter.off(event, listener)
	}
	once(event, listener){
		this.emitter.once(event, listener)
	}
	set mictime(mictime){
		this.Mictime = mictime
	}
	nativeFullscreen(media){
		if (media.requestFullscreen) {
			media.requestFullscreen();
		} else if (media.mozRequestFullScreen) {
			media.mozRequestFullScreen();
		} else if (media.webkitRequestFullScreen) {
			media.webkitRequestFullScreen();
		} else if (media.webkitEnterFullscreen) {
			media.webkitEnterFullscreen();
		}
	}
	transformFullscreen(){
		let myVideo = this.el.parentElement
		this.videoParentH = myVideo.getBoundingClientRect().height
		this.videoParentW = myVideo.getBoundingClientRect().width
		let w = document.documentElement.clientWidth || document.body.clientWidth
		let h = document.documentElement.clientHeight || document.body.clientHeigth
		let cha = Math.abs(h - w) / 2;
		this.el.style.width = myVideo.style.width = h + 'px'
		this.el.style.height = myVideo.style.height = w + 'px'
		myVideo.style.position = 'fixed'
		myVideo.style.zIndex = 2000
		myVideo.style.top = 0
		myVideo.style.transform = 'translate(-' + cha + 'px,' + cha + 'px) rotate(90deg)'
	}
	cancelTransformFullscreen(){
		let myVideo = this.el.parentElement
		this.el.style.width = myVideo.style.width = this.videoParentW + 'px'
		this.el.style.height = myVideo.style.height = this.videoParentH + 'px'
		myVideo.style.position = 'static'
		myVideo.style.transform = 'none'
	}
	judgeOnorientation(){
		let width = document.documentElement.clientWidth,height =  document.documentElement.clientHeight
		if(this.palyerWrap){
			if (width >= height) {
				this.palyerWrap.setAttribute('data-orientation','landscape')
			}else{
				this.palyerWrap.setAttribute('data-orientation','portrait')
			}
		}
	}
	orientationchange(){
		this.emitter.trigger(playerEvents.H5_PLAYER_ORIENTATIONCHANGE)
		setTimeout(()=>{
			this.judgeOnorientation()
		},300)
	}
	handleOnorientation(){
		window.addEventListener('orientationchange', this.orientationchange, false)
	}
	removeEvent(){
		window.removeEventListener('orientationchange', this.orientationchange, false)
	}
	judgeIsSeek(){
		console.log(this.media.buffered.end(0) - this.media.currentTime)
		if(this.media.buffered.length && !isNaN(this.media.buffered.end(0))){
			if((this.media.buffered.end(0) - this.media.currentTime) > 3){
				this.media.currentTime = this.media.buffered.end(0) - 1
			}
		}
	}
	openLazySeek(){
		fullScreenPlayer.lazySeekTimer = setInterval(()=>{
			this.judgeIsSeek()
		},10 * 60 * 1000)
	}
	errorRefresh(){
		window.location.reload()
	}
	addRefresh(){
		if(this.noticeWrap){
			this.el.querySelector('.refresh-player-icon').addEventListener('click',this.errorRefresh)
		}
	}
	removeRefresh(){
		if(this.noticeWrap){
			this.el.querySelector('.refresh-player-icon').removeEventListener('click',this.errorRefresh)
		}
	}
	initloadingChecker(){
		let lastPlayPos = 0;
		let currentPlayPos = 0;
		let bufferingDetected = false;
		this.loadingChecker = setInterval(() => {
				if (this.enableloadingChecker) {
						// whether the video is buffering
						currentPlayPos = this.media.currentTime;
						if (!bufferingDetected
								&& currentPlayPos === lastPlayPos
								&& !this.media.paused) {
								this.videoLoad.style.display = 'block'
								bufferingDetected = true;
						}
						if (bufferingDetected
								&& currentPlayPos > lastPlayPos
								&& !this.media.paused) {
								this.videoLoad.style.display = 'none'
								bufferingDetected = false;
						}
						lastPlayPos = currentPlayPos;
				}
		}, 100);
	}
	initNodePlayer(autoPlay){
		if(!this.FlvPlayer.isSupported()){
			this.nodePlayer = null
			if(document.body.classList.contains('flv-container-wrap')){
				document.body.classList.remove('flv-container-wrap')
			}
			this.videoLoad.style.display = 'none'
			this.lineLoad.style.display = 'none'
			this.flvErrorTips.style.display = 'block'
			setTimeout(()=> {
				this.destroy()
				this.emitter.trigger(playerEvents.FLV_ERROR)
				if (typeof(this.flvErrorCallback) === 'function') {
					this.flvErrorCallback()
				}
			}, 1000)
		}else{
			this.nodePlayer = new this.FlvPlayer({
			    container: this.el,
			    url: this.hlsUrl,
			    decoder: 'https://flvplayer.js.org/uncompiled/flvplayer-decoder-multiple.js',
			    debug: true,
			    live: true,
			    autoPlay: autoPlay,
			    hasAudio: true,
			    width: 960,
			    height: 540,
			});
		}
	}
}
